package com.cy.module;

import com.cy.config.EnumConst;
import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.RoleLabel;
import com.cy.model.User;
import com.cy.model.UserMapCompany;
import com.cy.model.UserMapRole;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@ControllerBind(controllerKey = "/clmp/user")
public class UserController extends WebApiController {

    @Override
    public void index() {
        User user = getModel(User.class);
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        Page<User> userPage = User.dao.paginate(page, pageSize, "u.*,MIN(umr.user_role_level) AS umrLevel,umc.company_id,c.name AS companyName,GROUP_CONCAT(CONCAT(r.role_id,'-',r.level)) AS roleInfos", user);
        renderBuiPage(userPage, 200);
    }

    @Override
    public void update() {
        Long id = getParaToLong();
        User tempUser = getModel(User.class);
        if(null == tempUser.getBirthDay())
            tempUser.remove("birth_day");
        User user = null;
        Map<String,String[]> paraMap = getParaMap();
        String nick_name,sexStr;
        Integer sex;
        boolean updateRole = true;
        if (null != paraMap){
            if(null != paraMap.get("user.nick_name")){
                nick_name = paraMap.get("user.nick_name")[0];
                try {
                    nick_name = URLDecoder.decode(URLDecoder.decode(nick_name, "UTF-8"), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                tempUser.setNickName(nick_name);
            }
            if(null != paraMap.get("sex")){
                sexStr = paraMap.get("sex")[0];
                if (StringUtils.isNotBlank(sexStr)){
                    sex = Integer.parseInt(sexStr);
                    tempUser.setSex(sex);
                }
            }
            user = User.dao.findById(id);
            user.cover(tempUser);
            if(null != paraMap.get("newPassword") && null != paraMap.get("oldPassword")){
                String newPassword = paraMap.get("newPassword")[0];
                String oldPassword = paraMap.get("oldPassword")[0];
                if (StringUtils.isNotBlank(newPassword) && StringUtils.isNotBlank(oldPassword)) {
                    if (!user.matchPassword(oldPassword)) {
                        renderStatus(EnumConst.RetCode.USERNAME_OR_PASSWORD_ERROR.getCode(), "输入的旧密码不正确，请重新尝试。");
                        return;
                    }
                    user.setPassword(newPassword).entryptPassword();
                }
            }
            Long level = getParaToLong("level");
            if(paraMap.get("userRoles") != null || level != null){
                String roleStr = paraMap.get("userRoles")[0];
                if(StringUtils.isNotEmpty(roleStr)){
                    String [] roles = roleStr.split("-");
                    for(String r :roles){
                        updateRole = userMapRole(r,user, level);
                    }
                }
            }
            if(null != paraMap.get("removeRoles")){
                String rmRoleStr = paraMap.get("removeRoles")[0];
                if(StringUtils.isNotEmpty(rmRoleStr)) {
                    String[] rmRoles = rmRoleStr.split("-");
                    for(String r :rmRoles){
                        long rmRole = Integer.parseInt(r);
                        UserMapRole rmMap = UserMapRole.dao.findExistsRole(user.getUserId(),rmRole);
                        if (null != rmMap){
                            updateRole = rmMap.delete();
                        }
                    }
                }
            }
            Long companyId = getParaToLong("company_id");
            UserMapCompany umc = UserMapCompany.dao.findByUser(id);
            if (umc == null){
                if (companyId != null){
                    new UserMapCompany().setCompanyId(companyId).setUserId(id).save();
                }
            } else {
                if (companyId != null){
                    umc.setCompanyId(companyId);
                    umc.update();
                } else {
                    umc.delete();
                }
            }
        }

        if (user != null && (user.update() || updateRole)) {
            renderSuccess();
        } else {
            renderFail();
        }
    }

    private boolean userMapRole(String roleStr, User user, Long level){
        long role = Integer.parseInt(roleStr);
        UserMapRole mapRole = UserMapRole.dao.findExistsRole(user.getUserId(),role);
        RoleLabel roleLabel = RoleLabel.dao.findById(role);
        if(mapRole == null){
            mapRole = new UserMapRole();
            mapRole.setUserId(user.getUserId()).setCreateTime(new Date()).setRoleId(role).setStatue(1);
            if (roleLabel.getLevel() == 0)//测试人员
                mapRole.setUserRoleLevel(level);
            return mapRole.save();
        }
        if (roleLabel.getLevel() == 0){//测试人员
            return mapRole.setUserRoleLevel(level).update();
        }
        return true;
    }

    public void getUser(){
        String mobile = getPara("mobile");
        Map<String, Object> result = new HashMap<>(2);
        if (StringUtils.isBlank(mobile)){
            result.put("status", 0);
            result.put("msg", "参数为空");
            renderJson(result);
            return;
        }
        mobile = mobile.replaceAll("^\\+86|-", "");
        User user = User.dao.findByMobile(mobile);
        if (user != null){
            result.put("status", 1);
            result.put("user", user);
        } else {
            result.put("status", 0);
            result.put("msg", "无此用户");
        }
        renderJson(result);
    }

}